#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2022/3/6 15:07
# @Author  : FLC
# @Contact : beifeng107@foxmail.com
# @File    : demo1.py
# @Software: PyCharm
import logging

from flask import Flask, request
from flask_restx import Api, Resource, Namespace
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import *

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = r"sqlite:///./demo.sqlite"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True

api = Api(app)
db = SQLAlchemy(app)


class ProjectTable(db.Model):
    project_id = Column(Integer, primary_key=True)
    project_name = Column(String(50), unique=True, nullable=False)
    project_num = Column(String(20), unique=True, nullable=False)
    project_description = Column(Text)
    project_status = Column(String(10), nullable=False, default="open")


project_ns = Namespace("project", "project management")


@project_ns.route("")
class Project(Resource):

    get_parser = api.parser()
    get_parser.add_argument("id", type=int, location="args")

    @project_ns.expect(get_parser)
    def get(self):
        """
        查询项目
        :return:
        """
        logging.info("get project")
        project_id = request.args.get("id")
        if project_id:
            record = ProjectTable.query.filter_by(project_id=project_id).all()
        else:
            record = ProjectTable.query.all()
        if record:
            res = {"code": "0",
                   "msg": "执行成功",
                   "projects": {}
                   }

            for r in record:
                res["projects"].update({r.project_id: {
                           "name": r.project_name,
                           "num": r.project_num,
                           "description": r.project_description,
                           "status": r.project_status
                       },})
            return res
        else:
            return {"code": "400001", "msg": "项目不存在"}

    post_parser = api.parser()
    post_parser.add_argument("id", type=int, required=True, location="json")
    post_parser.add_argument("name", type=str, required=True, location="json")
    post_parser.add_argument("code", type=str, required=True, location="json")
    post_parser.add_argument("description", type=str, location="json")
    post_parser.add_argument("status", type=str, location="json")

    @project_ns.expect(post_parser)
    def post(self):
        """
        创建项目
        :return:
        """
        logging.info("create project")
        datas = request.json
        record = ProjectTable.query.filter_by(project_id=datas.get("id")).first()
        if not record:
            project = ProjectTable()
            project.project_id = datas.get("id")
            project.project_name = datas.get("name")
            project.project_num = datas.get("code")
            project.project_description = datas.get("description")
            project.project_status = datas.get("status")
            db.session.add(project)
            db.session.commit()
            db.session.close()
            return {"code": "0", "msg": "执行成功"}
        else:
            return {"code": "400002", "msg": "项目已经存在"}

    put_parser = api.parser()
    put_parser.add_argument("id", type=int, required=True, location="json")
    put_parser.add_argument("name", type=str, location="json")
    put_parser.add_argument("code", type=str, location="json")
    put_parser.add_argument("description", type=str, location="json")
    put_parser.add_argument("status", type=str, location="json")

    @project_ns.expect(put_parser)
    def put(self):
        """修改项目"""
        logging.info("update project")
        datas = request.json
        record = ProjectTable.query.filter_by(project_id=datas.get("id")).first()
        if record:
            record.project_name = datas.get("name")
            record.project_num = datas.get("code")
            record.project_description = datas.get("description")
            record.project_status = datas.get("status")
            db.session.commit()
            db.session.close()
            return {"code": "0", "msg": "执行成功"}
        else:
            return {"code": "400001", "msg": "项目不存在"}

    delete_parser = api.parser()
    delete_parser.add_argument("id", type=int, required=True, location="args")

    @project_ns.expect(delete_parser)
    def delete(self):
        """
        删除项目
        """
        logging.info("delete project")
        project_id = request.args.get("id")
        record = ProjectTable.query.filter_by(project_id=project_id).first()
        if record:
            db.session.delete(record)
            db.session.commit()
            db.session.close()
            return {"code": "0", "msg": "执行成功"}
        else:
            return {"code": "400001", "msg": "项目不存在"}


api.add_namespace(project_ns, "/project")

if __name__ == '__main__':
    app.run(debug=True)
